package helpers;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Banco {

	private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	private static final String dbName = "loja";
	private static final String connectionURL = "jdbc:derby:" + dbName
			+ ";create=true";

	private static Connection conn = null;
	private static Statement s;
	private static ResultSet rs;

	static {
		connect();
	}

	private static void connect() {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(connectionURL);
		} catch (java.lang.ClassNotFoundException e) {
			Logger.erro("ClassNotFoundException: ");
			Logger.erro(e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static PreparedStatement prepareStatement(String sql)
			throws SQLException {
		return conn.prepareStatement(sql);
	}

	public static ResultSet retrieveQuery(String sql) {
		rs = null;

		try {
			s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = s.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public static int getQuantidade(String sql) {
		try {
			s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = s.executeQuery(sql);
			rs.next();
			return rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static boolean executePreparedStatement(PreparedStatement ps) {
		try {
			return ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean executeQuery(String sql) {
		try {
			s = conn.createStatement();
			return s.execute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

}
